export class SelectionHandler {
  constructor(editorElement) {
    this.editor = editorElement
    this.currentRange = null
  }

  getSelection() {
    return window.getSelection()
  }

  saveSelection() {
    const sel = this.getSelection()
    if (sel && sel.rangeCount > 0) {
      this.currentRange = sel.getRangeAt(0)
      return true
    }
    return false
  }

  restoreSelection() {
    if (this.currentRange) {
      const sel = this.getSelection()
      sel.removeAllRanges()
      sel.addRange(this.currentRange)
      return true
    }
    return false
  }

  lockSelection() {
    const sel = this.getSelection()
    if (sel && !sel.isCollapsed) {
      const range = sel.getRangeAt(0)

      // 检查是否已经在锁定区域内
      let startNode = range.startContainer
      let endNode = range.endContainer

      // 向上查找锁定区域
      while (startNode && startNode !== this.editor) {
        if (startNode.contentEditable === 'false') {
          return null // 已在锁定区域内
        }
        startNode = startNode.parentNode
      }

      while (endNode && endNode !== this.editor) {
        if (endNode.contentEditable === 'false') {
          return null // 已在锁定区域内
        }
        endNode = endNode.parentNode
      }

      const content = range.extractContents()
      const span = document.createElement('span')
      span.className = 'locked'
      span.style.cssText = `
        background: #f0f9ff;
        padding: 2px 6px;
        border-radius: 4px;
        border: 1px solid #409eff;
        color: #409eff;
        font-weight: 500;
      `
      span.contentEditable = 'false'
      span.appendChild(content)
      range.insertNode(span)

      // 恢复选区到新创建的锁定区域
      const newRange = document.createRange()
      newRange.selectNodeContents(span)
      const selection = this.getSelection()
      selection.removeAllRanges()
      selection.addRange(newRange)

      return span
    }
    return null
  }

  isSelectionValid() {
    const sel = this.getSelection()
    return sel && !sel.isCollapsed
  }

  getSelectedText() {
    const sel = this.getSelection()
    return sel ? sel.toString() : ''
  }

  clearSelection() {
    const sel = this.getSelection()
    if (sel) {
      sel.removeAllRanges()
    }
  }
}
